package com.meixun.xuanke.course.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.meixun.xuanke.course.model.User;
import com.meixun.xuanke.course.util.ParamUtil;
import com.meixun.xuanke.course.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Configuration
public class BaseInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate redisTemplate;
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "text/html;charset=UTF-8");//这句话是解决乱码的
        String token=request.getParameter("token");
        logger.info("token:"+token);
        if (!ParamUtil.isNull(token))
        {
            try
            {
                String userJson = (String) (redisTemplate.opsForValue().get("userJson:" +  token));
                if(!ParamUtil.isNull(userJson)){
                    User user= JSON.parseObject(userJson, new TypeReference<User>() {});

                    //验证当前请求的token是否是最后登录的token
                    String tokenOld = (String) (redisTemplate.opsForValue().get("tokenList:" +  user.getStuUserId()));
                    if (tokenOld != null && !tokenOld.equals(token))
                    {
                        // 踢出的token
                        redisTemplate.delete("userJson:" +  token);
                        //设置编码格式
                        response.setContentType("application/json;charset=UTF-8");
                        PrintWriter pw = response.getWriter();
                        pw.write(ResultUtil.getLoginInvalidJson());
                        //验证不通过,拦截返回
                        return false;
                    }else{
                        //刷新token
                        redisTemplate.opsForValue().set("userJson:" +  token,userJson,30, TimeUnit.MINUTES);
                        redisTemplate.opsForValue().set("tokenList:" +  user.getStuUserId(),token,30, TimeUnit.MINUTES);
                        request.setAttribute("userJson",userJson);

                    }
                }

            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return true;
    }

}
